package com.xxq.semester.controller.ai;

import com.xxq.semester.entity.utils.ResponseEntity;
import com.xxq.semester.service.ai.VideoPollingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/video")
@Tag(name = "AI视频生成", description = "AI视频生成相关接口")
public class VideoController {

    @Autowired
    private VideoPollingService videoPollingService;

    @Operation(summary = "开始轮询视频状态", description = "开始轮询指定requestId的视频生成状态，完成后发送邮件")
    @PostMapping("/start-polling")
    public ResponseEntity<Map<String, Object>> startPolling(
            @RequestBody Map<String, Object> requestBody) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String requestId = (String) requestBody.get("requestId");
            String email = (String) requestBody.get("email");
            
            if (requestId == null || requestId.isBlank()) {
                return ResponseEntity.error("requestId不能为空");
            }
            
            if (email == null || email.isBlank()) {
                return ResponseEntity.error("邮箱地址不能为空");
            }
            
            // 开始轮询任务
            String taskId = videoPollingService.startPolling(requestId, email);
            
            result.put("success", true);
            result.put("message", "已开始轮询视频生成状态");
            result.put("taskId", taskId);
            result.put("requestId", requestId);
            
            return ResponseEntity.success(result);
            
        } catch (Exception e) {
            return ResponseEntity.error("开始轮询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查询轮询任务状态", description = "查询轮询任务的当前状态")
    @GetMapping("/polling-status/{taskId}")
    public ResponseEntity<Map<String, Object>> getPollingStatus(@PathVariable String taskId) {
        
        try {
            Map<String, Object> status = videoPollingService.getTaskStatus(taskId);
            return ResponseEntity.success(status);
            
        } catch (Exception e) {
            return ResponseEntity.error("查询失败: " + e.getMessage());
        }
    }
}
